#include "HTTPRequest.h"
//#include <QDebug>

HTTPRequest::HTTPRequest(QObject *parent)
    :QNetworkAccessManager(parent)
{
    connect(this, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
}

HTTPRequest::~HTTPRequest()
{

}

bool HTTPRequest::checkURL(QUrl url)
{
    if (!url.isValid()) {
        qCritical() << "[!ERROR]: Invalid URL";
        return false;
    }

    if (url.scheme() == "http" || url.scheme() == "https")
    {
        if(url.scheme() == "https")
        {
            QSslConfiguration config = m_NetWorkRequest.sslConfiguration();
            config.setPeerVerifyMode(QSslSocket::VerifyNone);
            config.setProtocol(QSsl::TlsV1SslV3);
            m_NetWorkRequest.setSslConfiguration(config);
        }
    }
    else
    {
        qCritical() << "[!ERROR]: URL must start with 'http/https:'" << url.scheme();
        return false;
    }

    if (url.path().isEmpty()) {
        qCritical() << "[!ERROR]: URL has no path";
        return false;
    }
    //url.host(), url.port(80)

    qDebug() << "request header:" << m_NetWorkRequest.rawHeaderList();

    return true;
}

bool HTTPRequest::get(QUrl url)
{
    if(!checkURL(url))
        return false;

    m_baHttpData.clear();
    m_NetWorkRequest.setUrl(url);
    /******************设置http的header***********************/
    // m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    // m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    // m_NetWorkRequest.setRawHeader("Content-Disposition","form-data;name='doc';filename='a.txt'");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentLengthHeader,post_data.length());

    m_pNetWorkReply = QNetworkAccessManager::get(m_NetWorkRequest);//通过发送数据，返回值保存在reply指针里.
    connect(m_pNetWorkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT( onDownloadProgress(qint64 ,qint64 )));//download文件时进度
    connect(m_pNetWorkReply, SIGNAL(readyRead()),this, SLOT(onReadyRead()));
    connect(m_pNetWorkReply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT( onReplyError(QNetworkReply::NetworkError)) );//出现错误时发送此信号;

    return true;
}

bool HTTPRequest::post(QUrl url, QByteArray baData)
{
    if(!checkURL(url))
        return false;

    m_baHttpData.clear();
    m_NetWorkRequest.setUrl(url);
    /******************设置http的header***********************/
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    //m_NetWorkRequest.setRawHeader("Content-Disposition","form-data;name='doc';filename='a.txt'");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentLengthHeader,post_data.length());
    //m_NetWorkRequest.setRawHeader("Accept","*/*");
    //m_NetWorkRequest.setRawHeader("Accept-Language","zh-CN,zh;q=0.9");
    //m_NetWorkRequest.setRawHeader("Content-Type","application/x-www-form-urlencoded");
    //m_NetWorkRequest.setRawHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    //m_NetWorkRequest.setRawHeader("X-Requested-With:","XMLHttpRequest");
    //m_NetWorkRequest.setRawHeader("Referer","http://ip.taobao.com/ipSearch.html");

    m_pNetWorkReply = QNetworkAccessManager::post(m_NetWorkRequest, baData);//通过发送数据，返回值保存在reply指针里.
    connect(m_pNetWorkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT( onDownloadProgress(qint64 ,qint64 )));//download文件时进度
    connect(m_pNetWorkReply, SIGNAL(readyRead()),this, SLOT(onReadyRead()));
    connect(m_pNetWorkReply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT( onReplyError(QNetworkReply::NetworkError)) );//出现错误时发送此信号;

    return true;
}

void HTTPRequest::onReadyRead()
{
    qDebug() << "onReadyRead!!!";
    if(m_pNetWorkReply->error() == QNetworkReply::NoError)
    {
        m_baHttpData.append(m_pNetWorkReply->readAll());
    }
    else
    {
        qDebug() << "onReadyRead Err!!!";
    }
    //qDebug() << httpData;
}


/***************响应结束**************************/
void HTTPRequest::onFinished(QNetworkReply *reply){
    //获取响应的信息，状态码为200表示正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    //无错误返回
    if(reply->error() == QNetworkReply::NoError && status_code == 200)
    {
        emit s_finished(reply);
        qDebug() << "download Over:" << status_code << reply->error();

    }
    else
    {
        //处理错误
        qDebug() << "download Error!!!" << status_code << reply->error();
        emit s_finished(reply);
    }

    if(m_pNetWorkReply == reply)
        qDebug() << "m_pNetWorkReply == reply";

    reply->deleteLater();//要删除reply，但是不能在onFinished里直接delete，要调用deletelater;
    //m_pNetWorkReply = NULL;
}

void HTTPRequest::onDownloadProgress(qint64 a,qint64 b)
{
    //file.write(reply->readAll());
    qDebug()<<a<<"/"<<b;
}

void HTTPRequest::onReplyError(QNetworkReply::NetworkError e)
{
    qDebug()<<"onReplyError:"<<e;
}
